package model.client;

import model.client.request.LoginRequestMessage;
import model.entity.User;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;
import model.util.ChannelUtils;
import view.ChatInterface;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Description 客户端启动类
 * @author 14548
 */
public class Client {
    private User user;
    private ChatInterface chatInterface;

    public Client(User user, ChatInterface chatInterface) {
        new JFXPanel();
        this.user = user;
        this.chatInterface = chatInterface;
    }


    public void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ClientInitializer());

            Channel channel = bootstrap.connect("localhost", 8080)
                    .sync()
                    .channel();
            System.out.println("客户端启动成功，绑定端口8080");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            channel.writeAndFlush(new LoginRequestMessage(user.getId()));
            System.out.println("登入成功-----"+user.getId());

            System.out.println("当前线程是否是javafx线程:"+Platform.isFxApplicationThread());

            //默认聊天室的interfaceId为1，默认的ChannelGroup也为1
            String interfaceId = "1";


            chatInterface.setInterfaceId(interfaceId);
            chatInterface.setChannel(channel);

            //System.out.println("Client:Channel:"+channel);
            ChannelUtils.putChatInterface(interfaceId, chatInterface);

            //为channel绑定一个状态，这里用每个账户的昵称
            AttributeKey<String> nameAttrKey = AttributeKey.valueOf("name");
            channel.attr(nameAttrKey).set(user.getId());

            /*
            非javafx线程中执行javafx相关任务，必须在Platform.runLater中执行
            https://blog.csdn.net/u010061897/article/details/69358246
             */
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    chatInterface.setInterfaceId(interfaceId);
                    chatInterface.setChannel(channel);
                    System.out.println("打开聊天窗口");
                    System.out.println("Client:Channel"+ channel);
                    System.out.println("ChatInterface Channel"+chatInterface.getChannel());
                    chatInterface.start();
                    //更新JavaFX的主线程的代码放在此处
                }
            });

            //将客户端主线程阻塞
            channel.closeFuture().sync();



//            for(; ;) {
//                System.out.println("输入需要的功能，群聊输入creatGroup、" +
//                        "单聊输入sendToIndividuals、" +
//                        "创建群聊输入creatGroup");
//                System.out.println("直接输入信息则发送到所有人");
//                String info = br.readLine();
//                if(createGroup.equals(info)) {
//                    channel.writeAndFlush(new AllIdRequestMessage());
//                    System.out.println("输入邀请人username，每个username用空格分开");
//                    String userId = br.readLine();
//                    String[] s = userId.split(" +");
//                    List<String> username = Arrays.asList(s);
//                    channel.writeAndFlush(new CreateGroupRequestMessage(str, username));
//                }else if(sendToGroup.equals(info)) {
//                    System.out.println("输入想要发送到群的id:");
//                    info = br.readLine();
//                    System.out.println("输入要发送的信息:");
//                    content = br.readLine();
//                    channel.writeAndFlush(new SendToGroupRequestMessage(info, content, str));
//                } else if(sendToIndividuals.equals(info)) {
//                    System.out.println("输入接收者的id:");
//                    String receiverId = br.readLine();
//                    System.out.println("输入要发送的信息:");
//                    info = br.readLine();
//                    channel.writeAndFlush(new SendToIndividualsRequestMessage(str, receiverId, info));
//                } else {
//                    channel.writeAndFlush(new Message(str, info, interfaceId));
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭客户端");
            eventLoopGroup.shutdownGracefully();
        }
    }

}
